<?php

namespace App\Http\Middleware;

use App\Models\User\StaffModel;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class QwAuthMiddleware
{
    protected $corpId;
    protected $secret;
    protected $agentId;
    protected $redirectUri;

    public function __construct()
    {
        $this->corpId = env('QW_CORP_ID');
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, $appIdentifier)
    {
        $redirectUri = $request->fullUrl();
        switch ($appIdentifier) {
            case 'oa_user':
                $this->secret = env('QW_OA_USER_SECRET');
                $this->agentId = env('QW_OA_USER_AGENT_ID');
                break;
            case 'inventory':
                $this->secret = env('QW_INVENTORY_SECRET');
                $this->agentId = env('QW_INVENTORY_AGENT_ID');
                break;
            default:
                return response('Invalid app identifier', 400);
        }

        $qwUser = session('qw_user');
        if (empty($qwUser)) {
            if (!$request->has('code')) {
                $authUrl = $this->getAuthorizeUrl($redirectUri, 'pf');
                return redirect($authUrl);
            }

            $code = $request->input('code');
            try {
                $userInfo = $this->getUserInfo($code);
                // 在会话中存储用户信息
                session(['qw_user' => $userInfo]);
            } catch (\Exception $e) {
                return response('Error: ' . $e->getMessage(), 500);
            }
        } else {
            // 查询OA用户信息
            $oaUserInfo = StaffModel::query()->where('name', $qwUser['UserId'])->where('status', 1)->first();
            if (empty($oaUserInfo)) {
                return response('用户信息不存在或用户已被禁', 500);
            }
            session(['oa_user' => $oaUserInfo]);
        }
        return $next($request);
    }

    protected function getAuthorizeUrl($redirectUri, $state)
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->corpId .
            "&redirect_uri=" . urlencode($redirectUri) .
            "&response_type=code&scope=snsapi_base&state=" . $state . "#wechat_redirect";
        return $url;
    }

    protected function getAccessToken()
    {
        $accessToken = session('access_token');
        if (!empty($accessToken)) {
            return $accessToken;
        }
        $tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $this->corpId . "&corpsecret=" . $this->secret;
        $tokenResponse = Http::get($tokenUrl);
        $tokenArr = $tokenResponse->json();

        if (isset($tokenArr['access_token'])) {
            session(['access_token' => $tokenArr['access_token']], 7000);
            return $tokenArr['access_token'];
        } else {
            throw new \Exception("Failed to get access token: " . $tokenArr['errmsg']);
        }
    }

    protected function getUserInfo($code)
    {
        $accessToken = $this->getAccessToken();
        $userInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" . $accessToken . "&code=" . $code;
        $userInfoResponse = Http::get($userInfoUrl);
        $userInfoArr = $userInfoResponse->json();

        if (isset($userInfoArr['UserId'])) {
            return $userInfoArr;
        } else {
            throw new \Exception("Failed to get user info: " . $userInfoArr['errmsg']);
        }
    }
}
